<script setup>
import Item from "./Item.vue";
</script>
<template>
  <div>
    <div v-show="username">
      <div class="row" v-show="!isLoading">
        <Item v-for="u in users" :key="u.id" :user="u" />
      </div>
      <div v-show="isLoading" class="msg normalMsg">正在载入……</div>
    </div>
    <div v-show="!username">请输入要搜索的用户</div>
    <div v-show="errMsg" class="msg errMsg">发生错误：{{ errMsg }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      users: [],
      isLoading: false,
      username: "",
      errMsg: "",
    };
  },
  mounted() {
    this.$bus.$on("search", (username) => {
      this.username = username;
      this.searchUser();
    });
  },
  beforeDestroy() {
    this.$bus.$off("search");
  },
  methods: {
    searchUser() {
      this.isLoading = true;
      this.$http
        .get(`https://api.github.com/search/users?q=${this.username}`)
        .then(({ data }) => {
          console.log(data);
          this.users = [...data.items];
        })
        .catch((e) => {
          console.log(e);
          this.users = [];
          this.errMsg = e.toString();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
  },
};
</script>

<style scoped>
.msg {
  position: fixed;
  top: 50%;
  left: 50%;
  z-index: 99;
  padding: 1em;
}
.errMsg {
  background: red;
  color: white;
  border: 1px solid #ddd;
}
.normalMsg {
  background: blue;
  color: white;
  border: 1px solid #ddd;
}
</style>
